import os
import time
from django.template import loader
from django.conf import settings

from collections import OrderedDict
from contents import utils
from contents.models import ContentCategory


def generate_static_index_html():
    """生成静态化模板语言"""
    print('%s: generate_static_index_html' % time.ctime())
    categories = utils.get_categories()
    # 获取所有广告数据
    # 查询所有的广告类别
    contents = OrderedDict()
    content_categoryes = ContentCategory.objects.all()
    for content_category in content_categoryes:
        # 使用广告类别查询出所对应的广告类别
        contents[content_category.key] = content_category.content_set.filter(status=True).order_by('sequence')

    # 构造上下文
    context = {
        'categories': categories,
        'contents': contents,
    }
    # 获取首页魔板文件
    template = loader.get_template('index.html')
    # 渲染首页模板文件
    html_text = template.render(context)

    with open(os.path.join(settings.STATICFILES_DIRS[0], 'index.html'), 'w', encoding='utf-8') as f:
        f.write(html_text)